package com.gjy.statemachine.listener;

import com.gjy.statemachine.event.OrderStatusChangeEvent;
import com.gjy.statemachine.module.TbOrder;
import com.gjy.statemachine.repository.TbOrderRepository;
import com.gjy.statemachine.state.OrderStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-07-02 14:53:07
 */
@Component
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListenerImpl {
    private static final Logger log = LoggerFactory.getLogger(OrderStateListenerImpl.class);

    @Resource
    private TbOrderRepository tbOrderRepository;

    @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
    public void payTransition(Message<OrderStatusChangeEvent> message) {
        TbOrder order = (TbOrder) message.getHeaders().get("order");
        log.info("支付，状态机反馈信息：{}", message.getHeaders());
        //更新订单
        order.setStatus(OrderStatus.WAIT_DELIVER.getKey());
        tbOrderRepository.save(order);
        //TODO 其他业务
    }

    @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
    public void deliverTransition(Message<OrderStatusChangeEvent> message) {
        TbOrder order = (TbOrder) message.getHeaders().get("order");
        log.info("发货，状态机反馈信息：{}", message.getHeaders());
        //更新订单
        order.setStatus(OrderStatus.WAIT_RECEIVE.getKey());
        tbOrderRepository.save(order);
        //TODO 其他业务
    }

    @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
    public void receiveTransition(Message<OrderStatusChangeEvent> message) {
        TbOrder order = (TbOrder) message.getHeaders().get("order");
        log.info("确认收货，状态机反馈信息：{}", message.getHeaders());
        //更新订单
        order.setStatus(OrderStatus.FINISH.getKey());
        tbOrderRepository.save(order);
        //TODO 其他业务
    }

}
